package cn.edkuir.product.service.impl;

import cn.edkuir.product.service.CategoryBrandRelationService;
import cn.edkuir.product.vo.Catalog2Vo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.edkuir.common.utils.PageUtils;
import cn.edkuir.common.utils.Query;

import cn.edkuir.product.dao.CategoryDao;
import cn.edkuir.product.entity.CategoryEntity;
import cn.edkuir.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
//    @Autowired
//    private CategoryDao categoryDao;
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1. 查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2. 组装成父子的树形结构
        return entities.stream().filter(categoryEntity ->
                //找到所有的根目录, 递归查找其子菜单
                categoryEntity.getParentCid() == 0
        ).peek(categoryEntity ->
                categoryEntity.setChildren(getChildren(categoryEntity, entities))
        ).sorted((menu1, menu2) ->
                menu1.getSort() == null ? 0 : menu1.getSort() - (menu2.getSort() == null ? 0 : menu2.getSort())
        ).collect(Collectors.toList());
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单是否被别的地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    //找到catelogId的完整路径
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        //存储三级分类路径
        List<Long> path = new ArrayList<>();
        findParentPath(catelogId, path);

        return path.toArray(new Long[0]);
    }


    /**
     * 级联更新所有关联的数据
     * @param category
     * @CacheEvict 缓存失效
     */
    @Override
    @Transactional
//    @Caching(evict = {
//            @CacheEvict(value = "category", key = "'findLevelOneCategory'"),
//            @CacheEvict(value = "category", key = "'getCatalogJson'")
//    })
    @CacheEvict(value = "category", allEntries = true)
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }


    //查询所有一级分类
    @Override
    @Cacheable(value = {"category"}, key = "#root.method.name")
    public List<CategoryEntity> findLevelOneCategory() {
        System.out.println("findLevelOneCategory()方法调用");
        return baseMapper.selectList(
                new QueryWrapper<CategoryEntity>().eq("parent_cid", 0)
        );
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList, Long parentCid) {
        return selectList.stream().filter(item -> item.getParentCid().equals(parentCid))
                .collect(Collectors.toList());
    }


//    @Override
//    public Map<String, List<Catalog2Vo>> getCatalogJson() {
//        /**
//         *  1. 空结果缓存: 解决缓存穿透
//         *  2. 设置过期时间加随机值: 解决缓存雪崩
//         *  3. 加锁: 解决缓存击穿
//         */
//
//        //1.加入缓存逻辑
//        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
//        if(StringUtils.isEmpty(catalogJSON)) {
//            //2. 缓存中没有数据, 查询数据库
//            System.out.println("缓存不命中...");
//            return getCatalogJsonFromDbWithRedisLock();
//        }
//
//        //逆转为指定对象
//        return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>(){});
//    }


    //获取分类json数据
    @Override
    //代表当前方法的结果需要缓存, 如果缓存有, 则方法不需要调用, value表示缓存分区
    @Cacheable(value = {"category"}, key = "#root.method.name")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        //优化:先查出所有数据
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //1.查出所有一级分类
        List<CategoryEntity> levelOneCategorys = getParentCid(selectList, 0L);

        //2.封装数据
        Map<String, List<Catalog2Vo>> map = levelOneCategorys.stream().collect(Collectors.toMap(k -> {
            return k.getCatId().toString();
        }, v -> {
            //3.查到所有二级分类
            List<CategoryEntity> levelTwoCategorys = getParentCid(selectList, v.getCatId());
            //4. 封装指定vo
            List<Catalog2Vo> catalog2Vos = null;
            if (levelTwoCategorys != null) {
                catalog2Vos = levelTwoCategorys.stream().map(l2 -> {
                    //5. 找当前二级分类的三级分类
                    List<CategoryEntity> levelThreeCategorys = getParentCid(selectList, l2.getCatId());

                    //将三级分类封装为vo
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if (levelThreeCategorys != null) {
                        catalog3Vos = levelThreeCategorys.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString()
                                    , l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                    }

                    //catalog2Vo
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString()
                            , catalog3Vos, l2.getCatId().toString(), l2.getName());

                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));

        return map;
    }


    /**
     * 缓存数据一致性问题
     *      1. 双写模式
     *      2. 失效模式
     * @return
     */
    private Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        //锁的名字
        RLock lock = redissonClient.getLock("catalogJSON-lock");
        lock.lock();

        Map<String, List<Catalog2Vo>> data = null;
        try {
            data = getDataFromDb();
        } finally {
            lock.unlock();
        }
        return data;
    }


    private Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithRedisLock() {
        //占分布式锁, redis占坑
        //设置锁的过期时间, 避免死锁, 必须和加锁同步, 为原子操作
        String s = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", s, 300, TimeUnit.SECONDS);
        Map<String, List<Catalog2Vo>> data = null;
        if(lock) {
            System.out.println("获取分布式锁成功...");
            //加锁(占坑)成功, 执行业务代码
            try {
                data = getDataFromDb();
            } finally {
                //解锁, 如果业务时间太长, 超过了锁的过期时间, 则当前锁会被其他线程占有
                //redis脚本, 原子操作, lua脚本解锁
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then redis.call('del', KEYS[1]) else return 0 end";
                stringRedisTemplate.execute(new DefaultRedisScript<>(script, Integer.class)
                        , Arrays.asList("lock"), s);
            }
            return data;
        }else {
            System.out.println("获取分布式锁失败........");
            //加锁失败, 重试(自旋)
            //休眠100ms
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDbWithRedisLock();
        }
    }


    private synchronized Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithLocalLock() {
        //得到锁之后, 再去缓存中确定一次, 如果没有才需要查询
        return getDataFromDb();
    }


    private Map<String, List<Catalog2Vo>> getDataFromDb() {
        //得到锁之后, 再去缓存中确定一次, 如果没有才需要查询
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            });
        }
        System.out.println("查询了数据库" + Thread.currentThread().getName());

        //优化:先查出所有数据
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //1.查出所有一级分类
        List<CategoryEntity> levelOneCategorys = getParentCid(selectList, 0L);

        //2.封装数据
        Map<String, List<Catalog2Vo>> map = levelOneCategorys.stream().collect(Collectors.toMap(k -> {
            return k.getCatId().toString();
        }, v -> {
            //3.查到所有二级分类
            List<CategoryEntity> levelTwoCategorys = getParentCid(selectList, v.getParentCid());
            //4. 封装指定vo
            List<Catalog2Vo> catalog2Vos = null;
            if (levelTwoCategorys != null) {
                catalog2Vos = levelTwoCategorys.stream().map(l2 -> {
                    //5. 找当前二级分类的三级分类
                    List<CategoryEntity> levelThreeCategorys = getParentCid(selectList, l2.getParentCid());

                    //将三级分类封装为vo
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if (levelThreeCategorys != null) {
                        catalog3Vos = levelThreeCategorys.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString()
                                    , l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                    }

                    //catalog2Vo
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString()
                            , catalog3Vos, l2.getCatId().toString(), l2.getName());

                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));

        //6. 查到的数据放入redis缓存, 将对象转为json
        stringRedisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(map), 1, TimeUnit.DAYS);
        return map;
    }


    private void findParentPath(Long catelogId, List<Long> path) {
        CategoryEntity categoryEntity = this.getById(catelogId);
        if(categoryEntity.getParentCid() != 0) {
            findParentPath(categoryEntity.getParentCid(), path);
        }
        path.add(categoryEntity.getCatId());
    }


    //在总数组all中找到菜单root的所有子菜单, 递归查找
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all){
        return all.stream().filter(categoryEntity ->
                //在总数组中过滤出父菜单id等于root菜单id的值, 即root的子菜单
                categoryEntity.getParentCid().equals(root.getCatId())
        ).peek(categoryEntity ->
                //对于root的子菜单, 递归查找其子子菜单
                categoryEntity.setChildren(getChildren(categoryEntity, all))
        ).sorted((menu1, menu2) ->
                //排序
                menu1.getSort() == null ? 0 : menu1.getSort() - (menu2.getSort() == null ? 0 : menu2.getSort())
        ).collect(Collectors.toList());
    }

}